//
//  FogBugzConduit.m
//  Task Views
//
//  Created by Chris Karr on 2/26/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "FogBugzConduit.h"

@implementation FogBugzConduit

- (NSString *) getToken:(NSDictionary *) options
{
	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	NSString * token = [defaults valueForKey:@"FogBugz Token"];
	
	if (token != nil)
		return token;
	
	NSString * url = [NSString stringWithFormat:@"%@://%@/api.asp?cmd=logon&email=%@&password=%@",
					  [options valueForKey:@"protocol"], [options valueForKey:@"site"], [options valueForKey:@"username"],
					  [options valueForKey:@"password"], nil];
	
	NSError * error = nil;
	NSXMLDocument * xml = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:&error];
	
	if (xml != nil)
	{
		NSXMLElement * response = [xml rootElement];
		
		NSArray * tokens = [response elementsForName:@"token"];
		
		if ([tokens count] > 0)
		{
			[xml release];

			token = [[tokens objectAtIndex:0] stringValue];
		
			[defaults setValue:token forKey:@"FogBugz Token"];
			return token;
		}
	}
	else
		NSRunAlertPanel(@"Unable to access FogBugz", [error description], @"OK", nil, nil);
	
	[xml release];
	return nil;
}

- (NSArray *) fetchTasks:(NSDictionary *) options
{
	if ([options valueForKey:@"protocol"] == nil)
		[options setValue:@"https" forKey:@"protocol"];

	NSMutableArray * tasks = [NSMutableArray array];

	NSString * token = [self getToken:options];
	
	if (token != nil)
	{
		NSString * cats = @"ixBug,fOpen,sTitle,sLatestTextSummary,sProject,sArea,sPersonAssignedTo,sEmailAssignedTo,sStatus,sPriority,sFixFor,dtFixFor,hrsOrigEst,hrsCurrEst,hrsElapsed,sCustomerEmail,sCategory,dtOpened,dtResolved,dtClosed,dtLastUpdated,fReplied,fForwarded,sTicket,dtDue,sReleaseNotes,dtLastView,ixRelatedBugs";

		NSString * url = [NSString stringWithFormat:@"%@://%@/api.asp?cmd=search&q=.&token=%@&cols=%@",
						  [options valueForKey:@"protocol"],[options valueForKey:@"site"],token,cats,nil];
		
		NSError * error = nil;
		NSXMLDocument * xml = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:&error];
		
		if (xml != nil)
		{
			NSXMLElement * response = [xml rootElement];
			
			NSArray * casesArray = [response elementsForName:@"cases"];
			NSEnumerator * casesIter = [casesArray objectEnumerator];
			NSXMLElement * cases = nil;
			while (cases = [casesIter nextObject])
			{
				NSArray * caseArray = [cases elementsForName:@"case"];
				NSEnumerator * caseIter = [caseArray objectEnumerator];
				NSXMLElement * fbCase = nil;
				while (fbCase = [caseIter nextObject])
				{
					NSMutableDictionary * task = [NSMutableDictionary dictionary];

					NSArray * children = [fbCase children];
					NSEnumerator * childIter = [children objectEnumerator];
					NSXMLNode * child = nil;
					while (child = [childIter nextObject])
					{
						if ([child kind] == NSXMLElementKind)
						{
							NSXMLElement * field = (NSXMLElement *) child;

							NSString * name = [field name];
							id value = [field stringValue];
							
							if (value != nil && ![value isEqual:@""])
							{
								if ([name hasPrefix:@"hrs"])
									value = [NSNumber numberWithDouble:[value doubleValue]];
								else if ([name hasPrefix:@"dt"])
									value = [NSDate dateWithNaturalLanguageString:value];
								else if ([name hasPrefix:@"f"])
								{
									if ([value isEqual:@"true"])
										value = [NSNumber numberWithBool:YES];
									else
										value = [NSNumber numberWithBool:NO];
								}
								else if ([name isEqual:@"ixRelatedBugs"])
									value = [value componentsSeparatedByString:@","];

								[task setValue:value forKey:name];
							}
						}
					}
					
					[task setValue:[task valueForKey:@"sTitle"] forKey:@"name"];
					[task setValue:[NSString stringWithFormat:@"FogBugz (%@)", [options valueForKey:@"site"], nil] forKey:@"source"];
					[task setValue:[NSString stringWithFormat:@"FogBugz:%@", [task valueForKey:@"ixBug"]] forKey:@"id"];

					NSArray * related = [task valueForKey:@"ixRelatedBugs"];
					if (related != nil)
					{
						NSMutableArray * relatedItems = [NSMutableArray array];
						
						NSEnumerator * relatedIter = [related objectEnumerator];
						NSString * bugId = nil;
						while (bugId = [relatedIter nextObject])
							[relatedItems addObject:[NSString stringWithFormat:@"FogBugz:%@", bugId, nil]];
						
						[task setValue:relatedItems forKey:@"Related Tasks"];
					}
					
					[tasks addObject:task];
				}
			}
		}
		
		[xml release];
	}
			
	return tasks;
}

- (void) openExternalSite:(NSDictionary *) options
{
	if ([options valueForKey:@"protocol"] == nil)
		[options setValue:@"https" forKey:@"protocol"];
	
	NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@/", [options valueForKey:@"protocol"], 
										[options valueForKey:@"site"], nil]];
	
	[[NSWorkspace sharedWorkspace] openURL:url];
}


@end
